package com.m4f.city.web.controller.api;

import java.security.Principal;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.m4f.city.business.domain.Application;
import com.m4f.city.business.domain.InternalUser;
import com.m4f.city.exception.M4FApiException;
import com.m4f.city.utils.serializer.M4FJsonSerializer;

@Controller
@RequestMapping("/api/application")
public class ApplicationApiController extends ApiBaseController {
	
	/**
	 * Return the list of applications that the user has allowed to access.
	 */
	@RequestMapping("/user")
	@ResponseBody
	public Map<String, Object> getApplicationsOfUser(Principal principal, HttpServletResponse response) throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		InternalUser user = null;
		Collection<Application> applications = null;
		
		user = this.getInternalUser(principal);
		applications = this.serviceLocator.getApplicationService().getObjectsByIds(user.getApplicationIds(), "name", "", "", 0, 1000); // TODO change the end limit
				
		if(applications != null) {
			M4FJsonSerializer serializer = new M4FJsonSerializer(); // TODO inject!
			map = serializer.getMap(applications, "applications");
		}
		
		//throw new M4FApiException();
		
		return map;
	}
	
	/**
	 * Return the application info of one application if the user has allowed to access.
	 */
	@RequestMapping("/info/{applicationId}")
	@ResponseBody
	public Map<String, Object> getApplicationInfo(@PathVariable Long applicationId, Principal principal, HttpServletResponse response) throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		InternalUser user = null;
		Application application = null;
		
		user = this.getInternalUser(principal);
		if(user != null && user.getApplicationIds() != null && user.getApplicationIds().contains(applicationId)) {
			// Load the application
			application = this.serviceLocator.getApplicationService().getObjectById(applicationId);
		}
		
		if(application != null) {
			M4FJsonSerializer serializer = new M4FJsonSerializer(); // TODO inject!
			map = serializer.getMap(application);
		}
		
		return map;
	}
}
